import scrapy

from ScrapyObject.spiders.utils.url_utils import *

'''
scrapy crawl ydba -o ydba.json
https://1818123.com/
'''


class YdbaSpider(scrapy.Spider):
    name = "ydba"
    # 前缀
    prefix = 'https://'
    # 中缀
    website = '1818123'
    # 后缀
    suffix = '.com/'
    allowed_domains = [website + '.com']
    start_urls = [prefix + website + suffix]

    def __init__(self):
        self.i = 0

    def parse(self, response):
        content = get_data(response)
        video_urls = get_video_url_one(content)
        video_urls = list(set(video_urls))
        if len(video_urls):
            for video_url in video_urls:
                self.i = self.i + 1
                yield get_video_item(id=self.i, tags='', url=response.url, name='', pUrl='', vUrl=video_url)
        else:
            tags = response.xpath("//p[@style='margin-top: 10px; margin-left: 0;']/text()").extract()
            urls = response.xpath("//div[@class='selfScale']//a/@ href").extract()
            picture_urls = response.xpath("//div[@class='selfScale']//a//span/@ data-src").extract()
            names = response.xpath("//p[@class='textoverflow']/text()").extract()
            if len(tags) and len(urls) and len(picture_urls) and len(names):
                for i in range(len(picture_urls)):
                    self.i = self.i + 1
                    yield get_video_item(id=self.i, tags=tags[0].split("：")[-1].strip(), url=split_joint(self.prefix + self.website + self.suffix, urls[i]), name=names[i], pUrl=picture_urls[i], vUrl="")
        url_list = get_url(content)
        for url in url_list:
            if url.startswith('/') or url.startswith('html'):
                if '/vod/' in url:
                    yield scrapy.Request(split_joint(self.prefix + self.website + self.suffix, url), callback=self.parse)
